from appium import webdriver
from time import sleep
import subprocess

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

desired_caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "platformVersion": "9",
    "deviceName": '192.168.2.9:5555',
    "appPackage": "com.seven.qaml.burstserven",
    "appActivity": "com.seven.qaml.burstserven.ui.LoginActivity",
    'skipServerInstallation': False,
    'skipDeviceInitialization': False,
    "noReset": True
}
appium_server_url = 'http://127.0.0.1:4723'
driver = webdriver.Remote(appium_server_url, desired_caps)


# subprocess.run('adb shell am start -n com.seven.qaml.burstserven/.ui.LoginActivity', shell=True,
#                capture_output=True, text=True)


def check_and_click_template_button(driver):
    if driver.find_elements(By.ID, 'com.seven.qaml.burstserven:id/title_template'):
        try:
            driver.find_element(By.ID, 'com.seven.qaml.burstserven:id/button1').click()
            print("检测到 title_template，已点击 button1")
        except Exception as e:
            print(f"点击 button1 时出错: {str(e)}")


# login = WebDriverWait(driver, 10).until(
#     EC.element_to_be_clickable((By.ID, 'com.seven.qaml.burstserven:id/btn_info')))
# login.click()
#
# while True:
#     if driver.find_elements('id', 'com.seven.qaml.burstserven:id/text_ver'):
#         driver.keyevent(66)
#         break
sleep(5)
count = 0

while count < 200:
    check_and_click_template_button(driver)
    # driver.keyevent(9)
    register = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.ID, 'com.seven.qaml.burstserven:id/ll_menuScan_delaySchemeContainer')))
    register.click()
    # sleep(0.5)
    # driver.find_element(By.ID, 'com.seven.qaml.burstserven:id/btn_delay_add_group').click()
    group = WebDriverWait(driver, 15).until(
        EC.element_to_be_clickable((By.ID, 'com.seven.qaml.burstserven:id/btn_delay_add_group')))
    group.click()

    back = 1
    while back < 11:
        sleep(0.1)
        driver.keyevent(4)
        check_and_click_template_button(driver)
        # print(f"第{back}次back")
        back += 1

    while True:
        if driver.find_elements('id', 'com.seven.qaml.burstserven:id/text_ver'):
            driver.keyevent(66)
            break

    check_and_click_template_button(driver)
    count += 1
    print(f"already executed {count} times")
print('finished')
